package com.webyweather.android;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.common.io.CharStreams;
import com.webyweather.android.constant.Constants;
import com.webyweather.android.utils.LocationUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import static com.webyweather.android.constant.Constants.*;

/**
 * Created by tair_mustafaiev on 7/23/13.
 */
public class LaunchActivity extends Activity implements
        LocationListener,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    // Splash screen timer
    private static int SPLASH_TIME_OUT = 2000;

    // A request to connect to Location Services
    private LocationRequest mLocationRequest;

    // Stores the current instantiation of the location client in this object
    private LocationClient mLocationClient;

    private static final String TAG = "com.webyweather.android.LaunchActivity";

    private Location mCurrentLocation;

    private Handler mHandler;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.launch_activity);

        WebView webView = (WebView) findViewById(R.id.web_view);
        try {
            String customHtml = CharStreams.toString(new InputStreamReader(getAssets().open("launcher.html")));
            webView.loadDataWithBaseURL("file:///android_asset/", customHtml, "text/html", "utf-8", null);
        } catch (IOException e) {
            Log.e(TAG, "HTML Content read error", e);
        }

        // Create a new global location parameters object
        mLocationRequest = LocationRequest.create();
        /*
         * Set the update interval
         */
        mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);

        // Use high accuracy
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Set the interval ceiling to one minute
        mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
        mLocationClient = new LocationClient(this, this, this);

        mHandler = new Handler() {
            @Override
            public void handleMessage (Message msg) {
                Intent i = new Intent(LaunchActivity.this, WeByWeatherActivity.class);
                i.putExtra(Constants.LONGLAT, msg.getData());
                startActivity(i);
                // close this activity
                finish();
            }
        };

    }

    AsyncTask task = new AsyncTask() {

        @Override
        protected Object doInBackground (Object[] objects) {
            return null;
        }
    };


    @Override
    protected void onStart () {
        super.onStart();
        mLocationClient.connect();
    }

    @Override
    public void onConnected (Bundle b) {
        Bundle bundle = new Bundle();
        // Get the current location
        mCurrentLocation = mLocationClient.getLastLocation();
        double latitude = mCurrentLocation.getLatitude();
        double longitude = mCurrentLocation.getLongitude();

        bundle.putDouble(LATITUDE, latitude);
        bundle.putDouble(LONGITUDE, longitude);

        Message msg = new Message();
        msg.setData(bundle);
        mHandler.sendMessageDelayed(msg, SPLASH_TIME_OUT);
    }

    @Override
    public void onDisconnected () {
    }

    @Override
    public void onLocationChanged (Location location) {
        mCurrentLocation = location;
    }

    @Override
    public void onConnectionFailed (ConnectionResult connectionResult) {
    /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(
                        this,
                        LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);

                /*
                * Thrown if Google Play services canceled the original
                * PendingIntent
                */

            } catch (IntentSender.SendIntentException e) {
                // Log the error
                Log.e(TAG, "Error Occurred", e);
            }
        } else {
            // If no resolution is available, display a dialog to the user with the error.
            GooglePlayServicesUtil.getErrorDialog(
                    connectionResult.getErrorCode(),
                    this,
                    LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST).show();
        }
    }
}
